import { ref, Ref, unref, computed, watch, toRaw, h } from 'vue';
import type { BasicColumn } from '../types/table';
import { isEqual, cloneDeep } from 'lodash-es';
import { isArray, isString, isBoolean, isFunction } from '@/utils/is';
import { usePermission } from '@/hooks/web/usePermission';
import { ActionItem } from '@/components/DFTable';
import { renderEditCell } from '../components/editable';
import {
  // NTooltip,
  NIcon,
} from 'naive-ui';
// import { FormOutlined } from '@vicons/antd';
import { t } from '@/i18n';
import { useMixins } from '@/hooks/useMixins';
import { CaretUpSharp, CaretDownSharp } from '@vicons/ionicons5';
import { renderSvg } from '@/utils/index';
import { DFTableAction } from '@/components/DFTable';

export function useColumns(
  propsRef: any,
  fixedModal: any,
  editTableHandleDeleteFn: any,
  routerType: any
) {
  const columnsRef: any = ref(unref(propsRef).columns) as unknown as Ref<BasicColumn[]>;

  // console.log(propsRef);

  const tableFixedModalVisible = ref(false);

  let cacheColumns = unref(propsRef).columns;

  const hasIndex = unref(propsRef).hasIndex;

  const routeName = unref(propsRef).routeName;

  const getColumnsRef = computed(() => {
    const columns = unref(propsRef).isEditTable ? unref(columnsRef) : cloneDeep(unref(columnsRef));

    // console.log(columnsRef);

    handleActionColumn(propsRef, columns);
    if (!columns) return [];
    columns.forEach((m) => {
      m.renderSorterIcon = ({ order }) => {
        const style =
          'display: flex;align-items: center;flex-direction: column;transform: translateY(-6px);height: 9px;';
        return h('div', { style }, [
          h(NIcon, {
            color: order === 'descend' ? '#1d6eff' : '#C0C4CC',
            style: 'margin-bottom:-2px',
            size: 12,
            component: CaretUpSharp,
          }),
          h(NIcon, {
            color: order === 'ascend' ? '#1d6eff' : '#C0C4CC',
            style: 'margin-top:-2px',
            size: 12,
            component: CaretDownSharp,
          }),
        ]);
      };
    });

    // console.log(columns);

    return columns;
  });

  const { hasPermission } = usePermission();

  const { getTableLabelFn, language } = useMixins();

  function isIfShow(action: ActionItem): boolean {
    const ifShow = action.ifShow;

    let isIfShow = true;

    if (isBoolean(ifShow)) {
      isIfShow = ifShow;
    }
    if (isFunction(ifShow)) {
      isIfShow = ifShow(action);
    }
    return isIfShow;
  }

  // const renderTooltip = (trigger, content) => {
  //   return h(NTooltip, null, {
  //     trigger: () => trigger,
  //     default: () => content,
  //   });
  // };

  const getPageColumns = computed(() => {
    const pageColumns = unref(getColumnsRef);

    // console.log(getColumnsRef);
    const columns = unref(propsRef).isEditTable ? pageColumns : cloneDeep(pageColumns);

    if (hasIndex) {
      const obj = columns.find((item) => item.key === 'selection');

      const indexObj = columns.find((item) => item.key === 'index');

      if (!indexObj) {
        const indexColumn: BasicColumn = {
          ellipsis: { tooltip: true },
          key: 'index',
          title: t('common.table.order'),
          sorter: false,
          width: 80,
          minWidth: 80,
          fixed: 'left',
        };

        if (!obj) {
          columns.unshift(indexColumn);
        } else {
          columns.splice(1, 0, indexColumn);
        }
      }
    }

    return columns
      .filter((column) => {
        return hasPermission(column.auth as string[]) && isIfShow(column);
      })
      .map((column) => {
        //默认 ellipsis 为true
        column.ellipsis =
          typeof column.ellipsis === 'undefined' && column.key != 'action'
            ? { tooltip: true, lineClamp: 1 }
            : false;

        if (!column.title) {
          const title = getTableLabelFn(column, routeName) || '';

          if (column.required) {
            column.title = () => {
              return (
                h(
                  'div',
                  {
                    display: 'flex',
                    justifyContent: 'flex-start',
                  },
                  { default: () => 'Name' }
                ),
                [
                  h('div', {}, [
                    h('span', {
                      class: 'tableTip',
                      innerText: '*',
                    }),
                    h('span', {
                      innerText: title,
                    }),
                  ]),
                ]
              );
            };
          } else {
            column.title = title;
          }

          column.width =
            language.value === 'zh'
              ? column.width || ''
              : column.widthEn
              ? column.widthEn
              : column.width;
        }

        const { edit } = column;

        if (edit) {
          column.render = renderEditCell(column);
          // if (edit) {
          //   column.title = () => {
          //     return renderTooltip(
          //       h('span', {}, [
          //         h(
          //           'span',
          //           { style: { 'margin-right': '5px', width: '100px' } },
          //           getTableLabelFn(column, routeName)
          //         ),
          //         h(
          //           NIcon,
          //           {
          //             size: 14,
          //           },
          //           {
          //             default: () => h(FormOutlined),
          //           }
          //         ),
          //       ]),
          //       t('common.table.edit')
          //     );
          //   };
          // }
        }
        return column;
      });
  });

  watch(
    () => unref(propsRef).columns,
    (columns) => {
      columnsRef.value = columns;
      cacheColumns = columns;
    }
  );

  function handleActionColumn(propsRef: any, columns: BasicColumn[]) {
    const { actionColumn, isEditTable = false, showAddAndDelBtn = true } = unref(propsRef);

    let newActionColumn = actionColumn;

    if (isEditTable && showAddAndDelBtn && routerType !== 'check') {
      newActionColumn = {
        width: 90,
        widthEn: 105,
        label: 'operation',
        key: 'action',
        fixed: 'right',
        common: true,
        render(record) {
          const recordRow = toRaw(record);

          return h(DFTableAction as any, {
            style: 'button',
            actions: [
              {
                label: 'delete',
                type: 'primary',
                text: true,
                unAuth: true,
                onClick: () => {
                  editTableHandleDeleteFn && editTableHandleDeleteFn([recordRow.uuid]);
                  // handleDeleteFn(recordRow);
                },
              },
            ],
          });
        },
      };
    }

    if (!newActionColumn) return;

    !columns.find((col) => col.key === 'action') &&
      columns.push({
        ...(newActionColumn as any),
        title:
          (newActionColumn as any).title ||
          ((_column) => {
            return h(
              'div',
              {
                class: 'flex table-opera',
                style: {
                  cursor: propsRef.value.isGetFieldInfo ? 'pointer' : 'default',
                  'align-items': 'center',
                },
                onClick: openTableFixedDialogFn,
              },
              [
                h('span', null, { default: () => getTableLabelFn(newActionColumn, routeName) }),
                [
                  ...(propsRef.value.isGetFieldInfo
                    ? [
                        h(
                          renderSvg('tableFixedOptions'),
                          {
                            class: 'tableFixedOptions',
                            style: {
                              'margin-left': '8px',
                            },
                          },
                          { default: null }
                        ),
                      ]
                    : []),
                ],
              ]
            );
          }) ||
          getTableLabelFn(newActionColumn, routeName),
        width:
          language.value === 'zh'
            ? (newActionColumn as any).width || ''
            : (newActionColumn as any).widthEn
            ? (newActionColumn as any).widthEn
            : (newActionColumn as any).width,
      });
  }

  //设置
  function setColumns(columnList: string[]) {
    const columns: any[] = cloneDeep(columnList);
    if (!isArray(columns)) return;

    if (!columns.length) {
      columnsRef.value = [];
      return;
    }
    const cacheKeys = cacheColumns.map((item) => item.key);
    //针对拖拽排序
    if (!isString(columns[0])) {
      columnsRef.value = columns;
    } else {
      const newColumns: any[] = [];
      cacheColumns.forEach((item) => {
        if (columnList.includes(item.key)) {
          newColumns.push({ ...item });
        }
      });
      if (!isEqual(cacheKeys, columns)) {
        newColumns.sort((prev, next) => {
          return cacheKeys.indexOf(prev.key) - cacheKeys.indexOf(next.key);
        });
      }
      columnsRef.value = newColumns;
    }
  }

  function setColumns2(columnList: string[]) {
    columnsRef.value = columnList;
  }

  //获取
  function getColumns(): BasicColumn[] {
    const columns = toRaw(unref(getColumnsRef));

    return columns.map((item) => {
      return {
        ...item,
        title: item.title || getTableLabelFn(item, routeName),
        key: item.key,
        fixed: item.fixed || undefined,
        width:
          language.value === 'zh' ? item.width || '' : item.widthEn ? item.widthEn : item.width,
      };
    });
  }

  //获取原始
  function getCacheColumns(isKey?: boolean): any[] {
    return isKey ? cacheColumns.map((item) => item.key) : cacheColumns;
  }

  //更新原始数据单个字段
  function setCacheColumnsField(key: string | undefined, value: Partial<BasicColumn>) {
    if (!key || !value) {
      return;
    }

    cacheColumns.forEach((item) => {
      if (item.key === key) {
        Object.assign(item, value);
        return;
      }
    });
  }

  function openTableFixedDialogFn() {
    fixedModal.value && fixedModal.value.openModalFn();
  }

  return {
    getColumnsRef,
    getCacheColumns,
    setCacheColumnsField,
    setColumns,
    setColumns2,
    getColumns,
    getPageColumns,
    tableFixedModalVisible,
  };
}
